package 蓝桥算法;

import java.util.Random;
import java.util.StringJoiner;

public class 排序 {
    public static void main(String[] args) {
        //1.冒泡排序
        int[] arr01 = {5, 3, 2, 1, 7, 4}; //@101
        bubbling(arr01);

        //2.选择排序（小的上前）：冒前排序
        int[] arr02 = {5, 3, 2, 1, 7, 4};
        selectSort(arr02);
        System.out.println();

        //3.插入排序
        int[] arr03 = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48};
        Insert(arr03);

        //比较runtime
        elapsedTime();// 127 180 55
    }

    private static void elapsedTime() {
        int[] arr = new int[10000];
        Random r = new Random();
        StringJoiner sj = new StringJoiner(",","[","]");
        for (int i = 0; i < arr.length; i++) {
            arr[i] = r.nextInt(10000);
            sj.add(Integer.toString(arr[i]));
        }
        long start = System.currentTimeMillis();
        Insert(arr);
        long end = System.currentTimeMillis();
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }
        System.out.println();
        System.out.println(end-start);
    }

    private static void Insert(int[] arr03) {
        int startIndex = 0;
        for (int i = 0; i < arr03.length; i++) {
            if (arr03[i] > arr03[i + 1]) {
                startIndex = i + 1;
                break;
            }
        }
        for (int i = startIndex; i < arr03.length; i++) {
            int j = i;
            while (j > 0 && arr03[j] < arr03[j - 1]) {
                int temp = arr03[j];
                arr03[j] = arr03[j - 1];
                arr03[j - 1] = temp;
                j--;
            }
        }

        for (int i = 0; i < arr03.length; i++) {
            System.out.print(arr03[i] + " ");
        }

    }

    private static void bubbling(int[] arr01) {
        //{5, 3, 2, 1, 7, 4}
        for (int i = 0; i < arr01.length - 1; i++) {//外循环-1：最小数最后被顶到0索引
            for (int j = 0; j < arr01.length - 1; j++) { //内循环-1：两两比较 4-3
                if (arr01[j] > arr01[j + 1]) {
                    int temp = arr01[j];
                    arr01[j] = arr01[j + 1];
                    arr01[j + 1] = temp;
                }
            }
        }
        for (int i = 0; i < arr01.length; i++) {
            System.out.print(arr01[i] + " ");
        }
        System.out.println();
    }

    private static void selectSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] > arr[j]) {
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
